import useBaseQuery from "@/hooks/useBaseQuery";

import {createApi} from "@reduxjs/toolkit/query/react";
import {useRandomCode} from "@/hooks/useRandomCode";
const base64ToBlob = (base64, type = 'image/png') => {
    const byteCharacters = atob(base64);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    return new Blob([byteArray], { type });
};

const getFileNameUUID = () => {
    function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    return `${+new Date()}${rx()}${rx()}`;
};
const getFileTypeFromMimeType = (url) => {
    let mimeType = url.match(/data:(\S*);base64/)[1];
    const typeMap = {
        'image/jpeg': {
            suffix: 'jpeg',
            fileType: 1,
            type: 'image/jpeg',
        },
        'image/jpg': {
            suffix: 'jpg',
            fileType: 1,
            type: 'image/jpg',
        },
        'image/png': {
            suffix: 'png',
            fileType: 1,
            type: 'image/png',
        },
        'image/gif': {
            suffix: 'gif',
            fileType: 1,
            type: 'image/gif',
        },
        'application/pdf': {
            suffix: 'pdf',
            fileType: 4,
            type: 'application/pdf',
        },
        'text/plain': {
            suffix: 'txt',
            fileType: 4,
            type: 'text/plain',
        },
        'video/mp4': {
            suffix: 'mp4',
            fileType: 2,
            type: 'video/mp4',
        },
        'video/quicktime': {
            suffix:'mov',
            fileType: 2,
            type: 'video/quicktime',
        },
        'audio/mpeg': {
            suffix:'mp3',
            fileType: 3,
            type: 'audio/mpeg',
        },
        // 添加其他类型的映射
    };
    return typeMap[mimeType] || 'Unknown'
};

export const ossApi = createApi({
    reducerPath: 'ossApi',
    baseQuery: useBaseQuery('sys'),
    endpoints(build) {
        return {
            // http://192.168.200.122:3200/jeecgboot/sys/common/ossAccessInfo?_t=1737952110187
            ossAccessInfo: build.query({
                query(data) {
                    return {
                        url: 'common/ossAccessInfo',
                        method: "get",
                    }
                },
                async transformResponse(baseQueryReturnValue, meta, arg) {
                    try {
                        let {code,result} = baseQueryReturnValue;
                        if (code === 200) {
                            let typeInfo = getFileTypeFromMimeType(arg.fileUrl)
                            let addUrl = getFileNameUUID() + '.' + typeInfo.suffix;
                            console.log(typeInfo,addUrl);
                            result.key = result.key + addUrl;
                            let url = result.host+'/'+result.key
                            const formData = new FormData();
                            for (const key in result) {
                                if (result.hasOwnProperty(key)) {
                                    formData.append(key, result[key]);
                                }
                            }
                            let blob = null
                            // 转换 Base64 为 Blob
                            if(typeInfo.fileType === 2){
                                blob = base64ToBlob(arg.fileUrl.split(',')[1],typeInfo.type); // 去掉前缀部分
                            } else {
                                blob = base64ToBlob(arg.fileUrl.split(',')[1]); // 去掉前缀部分
                            }
                            // const blob = base64ToBlob(arg.fileUrl.split(',')[1]); // 去掉前缀部分
                            // formData.append('file', {
                            //     blob,
                            //     type: typeInfo.type, // 确保设置正确的 MIME 类型
                            //     name: addUrl, // 确保使用正确的文件名
                            // });
                            formData.append('file', blob, addUrl);

                            const uploadResponse = await fetch('https://fcaidata.oss-cn-shenzhen.aliyuncs.com/', {
                                method: 'post',
                                body: formData,
                            });

                            console.log(url);

                            return {
                                fileUrl: url,
                                fileName: addUrl,
                                ...typeInfo
                            };
                        }
                    } catch (error) {
                        console.error('Error in transformResponse:', error);
                        throw error;
                    }
                },
            }),

        }
    }
});


export const {
    useOssAccessInfoQuery,
} = ossApi;
